package com.atguigu.spzx.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.cart.service.CartService;
import com.atguigu.spzx.feign.product.ProductFeignClient;
import com.atguigu.spzx.model.entity.product.CartInfo;
import com.atguigu.spzx.model.entity.product.ProductSku;
import com.atguigu.spzx.model.entity.user.AuthContextUtil;
import com.atguigu.spzx.model.entity.user.UserInfo;
import com.atguigu.spzx.model.vo.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Mahone
 */
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Autowired
    private ProductFeignClient productFeignClient;

    @Override
    public void addToCart(Long skuId, Integer skuNum) {
        // 调用本地线程获取用户Id
        UserInfo userInfo = AuthContextUtil.getUserInfo();
        Long userId = userInfo.getId();
        // 判断缓存是否存在
        String cartJson = (String) redisTemplate.opsForHash().get("user:cart" + userId,skuId + "");
        CartInfo cartInfo = null;
        if (!StringUtils.isEmpty(cartJson)){
            // 如果该商品有缓存，修改数量
            cartInfo = JSON.parseObject(cartJson,CartInfo.class);
            cartInfo.setSkuNum(cartInfo.getSkuNum() + skuNum);
        }else {
            // 没有，则添加到购物车
            cartInfo = new CartInfo();
            // 根据skuId查询商品信息
            ProductSku productSku = productFeignClient.getBySkuId(skuId).getData();
            cartInfo.setUserId(userId);
            cartInfo.setSkuId(skuId);
            cartInfo.setSkuNum(skuNum);
            cartInfo.setCartPrice(productSku.getSalePrice().multiply(new BigDecimal(cartInfo.getSkuNum())));
            cartInfo.setImgUrl(productSku.getThumbImg());
            cartInfo.setSkuName(productSku.getSkuName());
            cartInfo.setIsChecked(1);
        }
        // 将购物车信息存入redis
        redisTemplate.opsForHash().put("user:cart" + userId,skuId + "", JSON.toJSONString(cartInfo));



    }

    @Override
    public List<CartInfo> cartList() {
        // 获取当前登录的用户信息
        Long userId = AuthContextUtil.getUserInfo().getId();

        // 获取数据
        List<Object> cartInfoList = redisTemplate.opsForHash().values("user:cart" + userId);
        if (!CollectionUtils.isEmpty(cartInfoList)){
           List<CartInfo> infoList = cartInfoList.stream().map(cartInfoJSON -> JSON.parseObject(cartInfoJSON.toString(),CartInfo.class))
                    .collect(Collectors.toList());
           return infoList;
        }
        return null;
    }

    @Override
    public List<CartInfo> getAllCkecked() {
        Long userId = AuthContextUtil.getUserInfo().getId();
        List<Object> cartInfoJsonList = redisTemplate.opsForHash().values("user:cart" + userId);
        List<CartInfo> cartInfos = new ArrayList<>();
        for (Object cartInfoJson : cartInfoJsonList) {
            CartInfo cartInfo = JSON.parseObject(cartInfoJson.toString(), CartInfo.class);
            if (cartInfo.getIsChecked().longValue() == 1){
                cartInfos.add(cartInfo);
            }
        }
        return cartInfos;
    }

    @Override
    public void deleteChecked() {
        Long userId = AuthContextUtil.getUserInfo().getId();
        List<Object> cartJsonObjectList = redisTemplate.opsForHash().values("user:cart" + userId);
        if (null != cartJsonObjectList && cartJsonObjectList.size() > 0){
            // 删除缓存
            redisTemplate.delete("user:cart" + userId);
            for (Object cartInfoObject : cartJsonObjectList) {
                CartInfo cartInfo = JSON.parseObject(cartInfoObject.toString(),CartInfo.class);
                if (cartInfo.getIsChecked().longValue() == 0){
                    // 未被选中保留缓存
                    redisTemplate.opsForHash().put("user:cart" + userId,cartInfo.getSkuId() + "",JSON.toJSONString(cartInfo));
                }
            }
        }
    }
}
